﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

using GeneralTool.CoreLibrary.Extensions;

using TaskHostLib;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var view = new TaskManagerView();
            view.Init(new TestTask());
            view.RunMethodEvent += this.View_RunMethodEvent;
            this.elementHost1.Child = view;
        }

        private async void View_RunMethodEvent(object sender, GeneralTool.CoreLibrary.TaskLib.TaskManager e)
        {
            var view = sender as TaskManagerView;
            var selected = view.SelectedTaskInfo;
            if (selected == null)
            {
               MessageBox.Show("没有选择一个接口","错误");
                return;
            }

           var tokenSource = new CancellationTokenSource();

        
            try
            {
               
                var result = await Task.Run(() =>
                {
                    try
                    {
                        //return taskManager.DoInterface(selected.Url, selected);
                        return e.DoInterface(selected);
                    }
                    catch (TaskCanceledException)
                    {
                        return "接口中止执行";
                    }
                });

                if (result != null)
                {
                    var msg = $"执行结束接口: [{selected.Method.Name}] {Environment.NewLine}执行结果: [{e.JsonCovert.SerializeObject(result)}]";
                    MessageBox.Show("执行结果:\r\n" + msg);
                }
                else
                {
                    MessageBox.Show("无返回");
                }
                   
            }
            catch (TaskCanceledException)
            {

            }
            catch (Exception ex)
            {
                var message = $"执行结束接口: [{selected.Method.Name}] 出错,错误信息:{ex.GetInnerExceptionMessage()} ";
                MessageBox.Show(message);
            }
            finally
            {
            }
        }
    }
}
